<?php

class ContributionsController extends AppController {

    public $uses = array('ModuleContributionReceipt', 'ModuleContributionType', 'ModuleMemberContribution','ModuleContributionPaymentType');


    public function contribution_types() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $response = $this->ModuleContributionType->getTypeList($organisation_id);

        return $this->_response($response);
    }


    public function get_payment_types() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $response = $this->ModuleContributionPaymentType->getPaymentTypes();

        return $this->_response($response);
    }



    public function contribution_type_detail() {
        $rules = array('required' => 'organisation_id','module_contribution_type_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $response = $this->ModuleContributionType->getType($organisation_id,$module_contribution_type_id);

        return $this->_response($response);
    }


    public function contribution_type_modify() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $name = $post['ModuleContributionType']['name'] = trim($post['ModuleContributionType']['name']);
        $description = $post['ModuleContributionType']['description'] = trim($post['ModuleContributionType']['description']);

        $error = false;

        if(empty($name)){
            $error[] = 'Contribution type name is required.';
        }
        /*if(empty($description)){
            $error[] = 'Contribution type description is required.';
        }*/

        if($error){
            $err_msg = implode('/n',$error);
            $response =  array('status' => 'failed', 'message' => $err_msg);
            return $this->_response($response);
        }

        $save = $this->ModuleContributionType->save($post);
        if($save){
            $return_data = array(
                'id'=> $this->ModuleContributionType->id,
                'name'=> $name,
                'description'=> $description
            );
            $response =  array('status' => 'success', 'message' => 'Contribution type saved successfully', 'data' => $return_data);
        }
        else{
            $response =  array('status' => 'failed', 'message' => 'Cannot save contribution type.');
        }


        return $this->_response($response);
    }


    public function contribution_type_delete() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $response = $this->ModuleContributionType->_delete($contribution_type_ids);

        return $this->_response($response);
    }


    public function collections() {
        $rules = array('required' => 'organisation_id','contribution_type_filter','receipt_dt');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $response = $this->ModuleMemberContribution->getList($organisation_id,$receipt_dt,$contribution_type_filter);

        return $this->_response($response);
    }


    public function save_contributions() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $error = false;
        $validate = $save = array();

        foreach($post_data as $key=>$value){
            $tr_data_id = trim($value['tr_data_id']);
            $receipt_dt = trim($value['receipt_dt']);
            $receipt_no = trim($value['receipt_no']);
            $organisation_account_id = trim($value['organisation_account_id']);
            $organisation_member_id = trim($value['organisation_member_id']);
            $module_contribution_type_id = trim($value['module_contribution_type_id']);
            $week = trim($value['week']);
            $month = trim($value['month']);
            $year = trim($value['year']);
            $amount = trim($value['amount']);
            $currency = trim($value['currency']);
            $module_contribution_payment_type_id = trim($value['module_contribution_payment_type_id']);
            $cheque_number = trim($value['cheque_number']);

            if(empty($receipt_dt)){
                $validate[$tr_data_id][] = 'Receipt Date is required.';
                $error = true;
            }
            if(empty($receipt_no)){
                $validate[$tr_data_id][] = 'Receipt No. is required.';
                $error = true;
            }
            if(empty($organisation_member_id)){
                $validate[$tr_data_id][] = 'Member is required.';
                $error = true;
            }
            if(empty($amount)){
                $validate[$tr_data_id][] = 'Amount is required.';
                $error = true;
            }
            if($module_contribution_payment_type_id == 2){//IF Cheque
                if(empty($cheque_number)){
                    $validate[$tr_data_id][] = 'Cheque Number is required.';
                    $error = true;
                }
            }


            $save[]= array(
                'ModuleContributionReceipt'=>array(
                    'organisation_id' => $organisation_id,
                    'organisation_account_id'=>$organisation_account_id,
                    'tr_data_id' =>$value['tr_data_id'],
                    'receipt_dt' =>$receipt_dt,
                    'receipt_no' =>$receipt_no
                ),
                'ModuleMemberContribution'=>array(
                    array(
                        'organisation_id' => $organisation_id,
                        'organisation_member_id' =>$organisation_member_id,
                        'module_contribution_type_id' =>$module_contribution_type_id,
                        'week' =>$week,
                        'month' =>$month,
                        'year' =>$year,
                        'module_contribution_payment_type_id' =>$module_contribution_payment_type_id,
                        'cheque_number' =>$cheque_number,
                        'cheque_status' =>'Not Cleared',
                        'amount' =>$amount,
                        'currency_id' =>$currency
                    )
                )
            );
        }

        if($error){
            $err_msg = "Form Validation Error";
            $response =  array('status' => 'failed', 'message' => $err_msg, 'data'=>$validate);
            return $this->_response($response);
        }

        foreach($save as $key=>$s){
            $response = $this->ModuleContributionReceipt->saveAll($s);
            if(!$response){
                $save[$key]['Error']= 'Record Not Saved.';
            }
        }

        $response =  array('status' => 'success', 'message' => 'Data Saved', 'data'=>$save);

        return $this->_response($response);
    }


    public function update_contributions() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $error = false;
        $validate = $save = array();

        foreach($post_data as $key=>$value){
            $tr_data_id = trim($value['contribution_id']);
            $receipt_dt = trim($value['receipt_dt']);
            $receipt_no = trim($value['receipt_no']);
            $organisation_account_id = trim($value['organisation_account_id']);
            $organisation_member_id = trim($value['organisation_member_id']);
            $module_contribution_type_id = trim($value['module_contribution_type_id']);
            $week = trim($value['week']);
            $month = trim($value['month']);
            $year = trim($value['year']);
            $amount = trim($value['amount']);
            $currency = trim($value['currency']);
            $module_contribution_payment_type_id = trim($value['module_contribution_payment_type_id']);
            $cheque_number = trim($value['cheque_number']);

            if(empty($receipt_dt)){
                $validate[$tr_data_id][] = 'Receipt Date is required.';
                $error = true;
            }
            if(empty($receipt_no)){
                $validate[$tr_data_id][] = 'Receipt No. is required.';
                $error = true;
            }
            if(empty($organisation_member_id)){
                $validate[$tr_data_id][] = 'Member is required.';
                $error = true;
            }
            if(empty($amount)){
                $validate[$tr_data_id][] = 'Amount is required.';
                $error = true;
            }
            if($module_contribution_payment_type_id == 2){//IF Cheque
                if(empty($cheque_number)){
                    $validate[$tr_data_id][] = 'Cheque Number is required.';
                    $error = true;
                }
            }

            $save[]= array(
                'ModuleContributionReceipt'=>array(
                    'id'=>$value['receipt_id'],
                    'organisation_id' => $organisation_id,
                    'organisation_account_id'=>$organisation_account_id,
                    'receipt_dt' =>$receipt_dt,
                    'receipt_no' =>$receipt_no
                ),
                'ModuleMemberContribution'=>array(
                    array(
                        'id'=>$value['contribution_id'],
                        'organisation_id' => $organisation_id,
                        'organisation_member_id' =>$organisation_member_id,
                        'module_contribution_type_id' =>$module_contribution_type_id,
                        'week' =>$week,
                        'month' =>$month,
                        'year' =>$year,
                        'amount' =>$amount,
                        'module_contribution_payment_type_id' =>$module_contribution_payment_type_id,
                        'cheque_status' =>'Not Cleared',
                        'cheque_number' =>$cheque_number,
                        'currency_id' =>$currency
                    )
                )
            );
        }

        if($error){
            $err_msg = "Form Validation Error";
            $response =  array('status' => 'failed', 'message' => $err_msg, 'data'=>$validate);
            return $this->_response($response);
        }

        foreach($save as $key=>$s){
            $response = $this->ModuleContributionReceipt->saveAll($s);
            if(!$response){
                $save[$key]['Error']= 'Record Not Saved.';
            }
        }

        $response =  array('status' => 'success', 'message' => 'Data Saved', 'data'=>$save);

        return $this->_response($response);
    }



    public function contacts($action = 'list') {

        $response = array();

        switch ($action) {
            case 'list':
                $response = $this->contactsList();
                break;

            case 'add':
                $response = $this->contactsAddContribution();
                break;

            case 'search':
                $response = $this->contactsSearch();
                break;
        }

        return $this->_response($response);
    }


    public function contactsSearch() {
        $limit = 10;

        $rules = array(
            'required' => 'organisation_id', 'term',
            'numeric' => 'limit'
        );

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $sql = sprintf("SELECT m.id, m.first_name, m.last_name, om.organisation_no, om.id FROM members m "
            . "INNER JOIN organisation_members om ON om.member_id = m.id "
            . "WHERE om.organisation_id = %d AND om.organisation_no LIKE '%s%%' "
            . "ORDER BY m.first_name, m.last_name "
            . "LIMIT %d",
            $organisation_id, $term, $limit);


        $result = $this->ModuleMemberContribution->query($sql);

        $response = array();

        foreach($result as $row) {
            $response[] = array(
                'label' => $row['m']['first_name'] . " " . $row['m']['last_name']." ( ".$row['om']['organisation_no']." )",
                'value' => $row['om']['organisation_no'],
                'organization_no' => $row['om']['organisation_no'],
                'organization_member_id' => $row['om']['id'],
                'member_id' => $row['m']['id']
            );
        }

        return $response;
    }


    public function getOverview() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $start_dt = date('Y-m-01');
        $end_dt = date('Y-m-t');

        $bar = $this->ModuleMemberContribution->getOverviewWeekly($organisation_id,$start_dt,$end_dt);
        $pie = $this->ModuleMemberContribution->getOverviewMonth($organisation_id,$start_dt,$end_dt);
        $response = array(
            'bar'=>$bar,
            'pie'=>$pie
        );
        return $this->_response($response);
    }


    public function history() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $total_pages = $this->ModuleMemberContribution->count_pagination($organisation_id,$receipt_dt,$receipt_no,$member_no,$contribution_type,$currency,$payment_type);

        $start = ($page - 1) * $limit; 			//first item to display on this page

        $data = $this->ModuleMemberContribution->load_pagination($organisation_id,$receipt_dt,$receipt_no,$member_no,$contribution_type,$currency,$payment_type,$start,$limit);

        $response = array(
            'total_pages'=>$total_pages,
            'data'=>$data
        );

        return $this->_response($response);
    }


    public function delete_contribution() {
        $rules = array('required' => 'organisation_id','contribution_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $response = $this->ModuleMemberContribution->delete_contribution($organisation_id,$contribution_id);

        return $this->_response($response);
    }


    public function cheques() {
        $rules = array('required' => 'organisation_id');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $total_pages = $this->ModuleMemberContribution->count_pagination($organisation_id,$receipt_dt,$receipt_no,$member_no,$contribution_type,$currency,$payment_type,$cheque_no,$cheque_status);

        $start = ($page - 1) * $limit; 			//first item to display on this page

        $data = $this->ModuleMemberContribution->load_pagination($organisation_id,$receipt_dt,$receipt_no,$member_no,$contribution_type,$currency,$payment_type,$start,$limit,$cheque_no,$cheque_status);

        $response = array(
            'total_pages'=>$total_pages,
            'data'=>$data
        );

        return $this->_response($response);
    }

    public function cheques_status() {
        $rules = array('required' => 'organisation_id','contribution_id','cheque_status');

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $response = $this->ModuleMemberContribution->cheques_status($organisation_id,$contribution_id,$cheque_status);

        return $this->_response($response);
    }



}
